package com.tc.controller;

import com.tc.entity.ResponseEnvelope;
import com.tc.entity.RestApiController;
import com.tc.entity.RestApiError;
import lombok.Getter;
import lombok.Setter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.MessageSource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by cai.tian on 2017/12/11.
 */
//@ControllerAdvice
public class RestApiResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
    private final Logger logger = LoggerFactory.getLogger(RestApiResponseEntityExceptionHandler.class);

    @Getter
    @Setter
    private String uncaughtExceptionErrorCode = "exception.uncaught.errorcode.default";

    /**
     * The spring message source used to localization the exception message
     */
    @Getter
    @Setter
    private MessageSource messageSource;

    @Getter
    @Setter
    private boolean logAsError = false;


    @ExceptionHandler(Exception.class)
    protected ResponseEntity<Object> handleUncaughtException(Exception ex, WebRequest request) {
        logger.error("The exception occur", ex);
        HttpHeaders headers = new HttpHeaders();
        HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;
        RestApiError restApiError = new RestApiError();
        restApiError.setStatusCode(status.value());
        restApiError.setMessage(messageSource.getMessage(uncaughtExceptionErrorCode, null, ex.getMessage(),
                request.getLocale()));
        restApiError.setRawMessage(ex.getMessage());
        ResponseEnvelope<Object> envelope = new ResponseEnvelope<Object>(restApiError);
        return handleExceptionInternal(ex, envelope, headers, status, request);
    }


}
